<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row type="flex" class="row-bg" justify="space-between">
        <el-col :span="24">
          <el-col :span="5" style=" margin-right: 10px">
            <el-input
              v-model="queryParam.containsAll"
              placeholder="搜索：用户名/昵称/手机号/邮箱"
              clearable
              maxlength="20"
              show-word-limit
              @keyup.enter.native="handleQuery"
            />
          </el-col>
          <el-button-group>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
            >查询
            </el-button>
            <el-button
              v-permission="['ROLE_ADMIN', 'user_list_insert']"
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
            >新增
            </el-button>
            <!--            <el-button
              v-permission="['ROLE_ADMIN', 'user_list_delete']"
              :loading="btnDeleteLoading"
              type="primary"
              icon="el-icon-delete"
              @click="handleBatchDelete"
            >
              删除
            </el-button>-->
          </el-button-group>
        </el-col>
      </el-row>
    </div>
    <el-table
      :loading="listLoading"
      :data="list"
      :header-cell-style="{'text-align':'center'}"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelected"
    >
      <!--<el-table-column align="center" label="-" width="95">
        <template v-slot="scope">{{ scope.$index+1 }}</template>
      </el-table-column>-->
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column type="index" label="-" width="50" align="center"/>
      <el-table-column label="用户名" prop="username"/>
      <el-table-column label="昵称" prop="nickname"/>
      <el-table-column label="手机号" prop="phone"/>
      <el-table-column label="邮箱" prop="email"/>
      <el-table-column fixed="right" label="操作" width="210" align="center">
        <template v-slot="{row, $index}">
          <el-tooltip content="详情" placement="top" :disabled="$index!==0">
            <el-button size="mini" icon="el-icon-document" circle @click="handleDetail(row, $index)"/>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top" :disabled="$index!==0">
            <el-button
              v-permission="['ROLE_ADMIN', 'user_list_update']"
              size="mini"
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleUpdate(row, $index)"
            />
          </el-tooltip>
          <el-tooltip content="复制" placement="top" :disabled="$index!==0">
            <el-button
              v-permission="['ROLE_ADMIN', 'user_list_copy']"
              size="mini"
              type="primary"
              icon="el-icon-document-copy"
              circle
              @click="handleCopy(row, $index)"
            />
          </el-tooltip>
          <el-tooltip v-if="row.isDisabled()" content="启用" placement="top" :disabled="$index!==0">
            <el-button
              v-permission="['ROLE_ADMIN', 'user_list_disable']"
              size="mini"
              type="danger"
              icon="el-icon-open"
              circle
              @click="handleEnable(row, $index)"
            />
          </el-tooltip>
          <el-tooltip v-if="!row.isDisabled()" content="禁用" placement="top" :disabled="$index!==0">
            <el-button
              v-permission="['ROLE_ADMIN', 'user_list_disable']"
              size="mini"
              type="success"
              icon="el-icon-turn-off"
              circle
              @click="handleDisable(row, $index)"
            />
          </el-tooltip>
          <!--<el-tooltip   content="删除" placement="top">
            <el-popconfirm title="是否确认删除？" placement="top" @confirm="handleDelete(row, $index)">
              <el-button
                slot="reference"
                v-permission="['ROLE_ADMIN', 'user_list_delete']"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                circle
                style="margin-left: 10px"
              />
            </el-popconfirm>
          </el-tooltip>-->
          <el-tooltip content="重置密码" placement="top" :disabled="$index!==0">
            <el-popconfirm title="是否确定重置用户密码？" placement="top" @confirm="handleResetPassword(row, $index)">
              <el-button
                slot="reference"
                v-permission="['ROLE_ADMIN', 'user_list_reset_password']"
                size="mini"
                type="warning"
                icon="el-icon-connection"
                circle
                style="margin-left: 10px"
              />
            </el-popconfirm>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        :current-page.sync="queryParam.page.number"
        :page-size.sync="queryParam.page.limit"
        :total.sync="queryParam.page.totalCount"
        :page-sizes="[3,10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleQuery"
        @current-change="handleQuery"
      />
    </div>
    <user-save-dialog
      v-permission="['ROLE_ADMIN', 'user_list_insert', 'user_list_update']"
      :row="selectedRow"
      :visible.sync="visibleSaveDialog"
      @ok="handleQuery"
    />
    <user-detail-drawer v-if="visibleDetailDrawer" :row="selectedRow" :visible.sync="visibleDetailDrawer"/>
  </div>
</template>

<script>
import User from '@/api/entity/User'
import Page from '@/utils/entity/Page'
import permission from '@/directive/permission'
import UserSaveDialog from '@/views/user/components/UserSaveDialog'
import UserDetailDrawer from '@/views/user/components/UserDetailDrawer'
import UserService from '@/api/UserService'
import OrderBy from '@/utils/entity/OrderBy'

export default {
  components: {UserSaveDialog, UserDetailDrawer},
  directives: {permission},
  data() {
    /**
     * @type {User[]}
     */
    const selectedRows = []
    /**
     * @type {User[]}
     */
    const list = []
    return {
      queryParam: new User({
        page: Page.ofDefault(),
        orderBy: [OrderBy.desc('id')]
      }),
      list,
      listLoading: true,
      btnDeleteLoading: false,
      selectedRows,
      selectedRow: new User(),
      visibleSaveDialog: false,
      visibleDetailDrawer: false
    }
  },
  created() {
    this.handleQuery()
  },
  methods: {
    async handleQuery() {
      this.listLoading = true
      /**
       *
       * @type {Result}
       */
      const result = await UserService.pageable(this.queryParam).finally(() => (this.listLoading = false))
      result
        .ifToastErrorMessage()
        .ifSuccess(() => {
          this.list = result.data.map(row => {
            row.visible = false
            return row
          })
          if (result.totalCount > 0 && result.rowCount === 0) {
            this.queryParam.page.number = result.pageCount
            this.handleQuery()
          }
        })
        .syncPageCount(this.queryParam.page)
    },
    /**
     *
     * @param rows {User[]}
     */
    handleSelected(rows) {
      this.selectedRows = rows
    },
    handleAdd() {
      this.selectedRow = new User()
      this.visibleSaveDialog = true
    },
    /**
     *
     * @param row {User}
     */
    handleUpdate(row) {
      this.selectedRow = new User(row)
      this.visibleSaveDialog = true
    },
    /**
     *
     * @param row {User}
     */
    handleCopy(row) {
      this.selectedRow = new User(row)
      this.selectedRow.id = null
      this.visibleSaveDialog = true
    },
    /**
     *
     * @param row {User}
     */
    handleDetail(row) {
      this.selectedRow = new User(row)
      this.visibleDetailDrawer = true
    },
    /**
     *
     * @param row {User}
     */
    async handleDisable(row) {
      this.listLoading = true
      const result = await UserService.disable(row.dv).finally(() => (this.listLoading = false))
      result
        .ifToastMessage('禁用成功', '禁用失败')
        .ifSuccess(() => this.handleQuery())
    },
    /**
     *
     * @param row {User}
     */
    async handleEnable(row) {
      this.listLoading = true
      const result = await UserService.enable(row.dv).finally(() => (this.listLoading = false))
      result
        .ifToastMessage('启用成功', '启用失败')
        .ifSuccess(() => this.handleQuery())
    },
    /**
     *
     * @param row {User}
     */
    async handleDelete(row) {
      this.listLoading = true
      const result = await UserService.markDeleteById(row.dv).finally(() => (this.listLoading = false))
      result
        .ifToastMessage('删除成功', '删除失败')
        .ifSuccess(() => this.handleQuery())
    },
    /**
     *
     * @param row {User}
     */
    async handleResetPassword(row) {
      this.listLoading = true
      const result = await UserService.resetPassword(row.dv).finally(() => (this.listLoading = false))
      result
        .ifToastMessage('密码重置成功', '密码重置失败')
        .dataFirst(newPassword => {
          this.$alert(`新密码为：${newPassword}`, '密码重置成功', {confirmButtonText: '确定'})
        })
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一行数据')
        return
      }
      this.$confirm('是否确认删除选中数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.btnDeleteLoading = true
        const result = await UserService.markDeleteByIds(this.selectedRows.map(row => row.dv)).finally(() => (this.btnDeleteLoading = false))
        result
          .ifToastMessage('删除成功', '删除失败')
          .ifSuccess(() => {
            this.handleQuery()
          })
      })
    }
  }
}
</script>
